﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace IloveRSS.Models.DataMap
{
    /// <summary>
    /// Sites services
    /// </summary>
    public class SitesMapRepository
    {
        private ILoveRSSDataContext dataContext;

        public SitesMapRepository(ILoveRSSDataContext dt)
        {
            this.dataContext = dt;
        }

        public IEnumerable<Sites> GetAllSites()
        {
            return dataContext.Sites;
        }

        //
        // TODO: Abstract class repository
        //

        /*
         *  if exist return site
         *  else return null 
         */
        public Sites ExistById(int siteId)
        {
            return dataContext.Sites.FirstOrDefault(site => site.ID == siteId);
        }

        /*
         *  if exist return site
         *  else return null 
         */
        public Sites ExistsByURL(String siteURL)
        {
            return dataContext.Sites.FirstOrDefault(site => site.SiteURL.Equals(siteURL));
        }

        /*
         * always return Site with siteURL
         */ 
        public Sites AddSite(String siteURL)
        {
            Sites site = ExistsByURL(siteURL); 
            if (null == site)
            {
                site = new Sites { SiteURL = siteURL };
                dataContext.Sites.InsertOnSubmit(site);
                dataContext.SubmitChanges();
            }
            return site;
        }

        public void Update(Sites s)
        {
            Sites site = ExistById(s.ID);
            site.SiteURL = s.SiteURL;
            site.ID = s.ID;
            dataContext.SubmitChanges();
        }

        public void RemoveSite(int siteID)
        {
            
            Sites site = ExistById(siteID);
            if (null != site)
            {
                dataContext.Sites.DeleteOnSubmit(site);
                dataContext.SubmitChanges();
            }
        }
    }
        public class SitesComparer: IEqualityComparer<Sites>
        {
            public bool Equals(Sites s1, Sites s2)
            {
                return (s1.SiteURL.Equals((s2.SiteURL)));
            }

            public int GetHashCode(Sites obj)
            {
                throw new NotImplementedException();
            }

        }
}